using DocumentCreationSystem.Models;
using Microsoft.Extensions.Logging;
using System.Text.Json;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 角色发展规划器 - 规划角色的成长轨迹和发展路径
    /// </summary>
    public class CharacterDevelopmentPlanner
    {
        private readonly ILogger<CharacterDevelopmentPlanner> _logger;
        private readonly IAIService _aiService;

        public CharacterDevelopmentPlanner(
            ILogger<CharacterDevelopmentPlanner> logger,
            IAIService aiService)
        {
            _logger = logger;
            _aiService = aiService;
        }

        /// <summary>
        /// 规划角色发展路径
        /// </summary>
        public async Task<CharacterDevelopmentPath> PlanCharacterDevelopmentAsync(
            Character character, 
            EnhancedUserIntent intent)
        {
            try
            {
                _logger.LogInformation($"为角色 {character.Name} 规划发展路径");

                var developmentPath = new CharacterDevelopmentPath
                {
                    CharacterId = character.Id.ToString(),
                    DevelopmentTheme = await DetermineDevelopmentThemeAsync(character, intent)
                };

                // 生成发展里程碑
                var milestones = await GenerateDevelopmentMilestonesAsync(character, intent);
                developmentPath.Milestones.AddRange(milestones);

                _logger.LogInformation($"为角色 {character.Name} 生成了 {milestones.Count} 个发展里程碑");
                return developmentPath;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"规划角色发展失败: {character.Name}");
                throw;
            }
        }

        /// <summary>
        /// 确定发展主题
        /// </summary>
        private async Task<string> DetermineDevelopmentThemeAsync(Character character, EnhancedUserIntent intent)
        {
            try
            {
                var prompt = $@"请为以下角色确定一个发展主题：

角色信息：
- 名称：{character.Name}
- 描述：{character.Description}
- 当前属性：{character.Attributes}

项目类型：{intent.ProjectContext?.ProjectType ?? "通用"}
用户需求：{intent.OriginalRequest}

请提供一个简洁的发展主题（如：从弱小到强大、从孤独到团结、从迷茫到坚定等）：";

                var response = await _aiService.GenerateTextAsync(prompt, 200, 0.7f);
                return response.Trim();
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "确定发展主题失败，使用默认主题");
                return "角色成长与发展";
            }
        }

        /// <summary>
        /// 生成发展里程碑
        /// </summary>
        private async Task<List<DevelopmentMilestone>> GenerateDevelopmentMilestonesAsync(
            Character character, 
            EnhancedUserIntent intent)
        {
            try
            {
                var prompt = $@"请为以下角色规划发展里程碑：

角色信息：
- 名称：{character.Name}
- 描述：{character.Description}
- 当前属性：{character.Attributes}
- 当前技能：{character.Skills}

请生成5-10个发展里程碑，每个里程碑包括：
1. 章节号（从1开始）
2. 事件描述
3. 属性变化（如果有）
4. 新技能（如果有）

格式：章节号|事件描述|属性变化|新技能";

                var response = await _aiService.GenerateTextAsync(prompt, 2000, 0.8f);
                return ParseDevelopmentMilestonesResponse(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成发展里程碑失败");
                return new List<DevelopmentMilestone>();
            }
        }

        /// <summary>
        /// 解析发展里程碑响应
        /// </summary>
        private List<DevelopmentMilestone> ParseDevelopmentMilestonesResponse(string response)
        {
            var milestones = new List<DevelopmentMilestone>();

            try
            {
                var lines = response.Split('\n', StringSplitOptions.RemoveEmptyEntries);
                
                foreach (var line in lines)
                {
                    var parts = line.Split('|');
                    if (parts.Length >= 2)
                    {
                        var milestone = new DevelopmentMilestone();
                        
                        // 解析章节号
                        if (int.TryParse(parts[0].Trim(), out var chapterNumber))
                        {
                            milestone.ChapterNumber = chapterNumber;
                        }
                        else
                        {
                            continue; // 跳过无效的行
                        }

                        // 解析事件描述
                        milestone.Event = parts[1].Trim();

                        // 解析属性变化
                        if (parts.Length > 2 && !string.IsNullOrWhiteSpace(parts[2]))
                        {
                            milestone.AttributeChanges = ParseAttributeChanges(parts[2].Trim());
                        }

                        // 解析新技能
                        if (parts.Length > 3 && !string.IsNullOrWhiteSpace(parts[3]))
                        {
                            milestone.NewSkills = ParseNewSkills(parts[3].Trim());
                        }

                        milestones.Add(milestone);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "解析发展里程碑响应失败");
            }

            return milestones.OrderBy(m => m.ChapterNumber).ToList();
        }

        /// <summary>
        /// 解析属性变化
        /// </summary>
        private Dictionary<string, object> ParseAttributeChanges(string attributeChangesText)
        {
            var changes = new Dictionary<string, object>();

            try
            {
                // 尝试解析格式如："力量+10,敏捷+5,境界=筑基期"
                var parts = attributeChangesText.Split(',', StringSplitOptions.RemoveEmptyEntries);
                
                foreach (var part in parts)
                {
                    var trimmedPart = part.Trim();
                    
                    if (trimmedPart.Contains('+'))
                    {
                        var keyValue = trimmedPart.Split('+');
                        if (keyValue.Length == 2 && int.TryParse(keyValue[1], out var increment))
                        {
                            changes[keyValue[0].Trim()] = $"+{increment}";
                        }
                    }
                    else if (trimmedPart.Contains('='))
                    {
                        var keyValue = trimmedPart.Split('=');
                        if (keyValue.Length == 2)
                        {
                            changes[keyValue[0].Trim()] = keyValue[1].Trim();
                        }
                    }
                    else if (trimmedPart.Contains('-'))
                    {
                        var keyValue = trimmedPart.Split('-');
                        if (keyValue.Length == 2 && int.TryParse(keyValue[1], out var decrement))
                        {
                            changes[keyValue[0].Trim()] = $"-{decrement}";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "解析属性变化失败");
            }

            return changes;
        }

        /// <summary>
        /// 解析新技能
        /// </summary>
        private List<string> ParseNewSkills(string newSkillsText)
        {
            try
            {
                return newSkillsText
                    .Split(',', StringSplitOptions.RemoveEmptyEntries)
                    .Select(skill => skill.Trim())
                    .Where(skill => !string.IsNullOrWhiteSpace(skill))
                    .ToList();
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "解析新技能失败");
                return new List<string>();
            }
        }

        /// <summary>
        /// 验证发展路径的合理性
        /// </summary>
        public async Task<DevelopmentValidationResult> ValidateDevelopmentPathAsync(
            CharacterDevelopmentPath developmentPath, 
            Character character)
        {
            try
            {
                _logger.LogInformation($"验证角色 {character.Name} 的发展路径");

                var result = new DevelopmentValidationResult
                {
                    IsValid = true,
                    ValidationTime = DateTime.Now
                };

                // 检查里程碑的逻辑顺序
                var orderIssues = ValidateMilestoneOrder(developmentPath.Milestones);
                result.Issues.AddRange(orderIssues);

                // 检查属性变化的合理性
                var attributeIssues = await ValidateAttributeChangesAsync(developmentPath.Milestones, character);
                result.Issues.AddRange(attributeIssues);

                // 检查技能学习的合理性
                var skillIssues = ValidateSkillProgression(developmentPath.Milestones);
                result.Issues.AddRange(skillIssues);

                // 计算发展路径评分
                result.Score = CalculateDevelopmentScore(developmentPath);

                result.IsValid = !result.Issues.Any();

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "验证发展路径失败");
                return new DevelopmentValidationResult { IsValid = false };
            }
        }

        /// <summary>
        /// 验证里程碑顺序
        /// </summary>
        private List<string> ValidateMilestoneOrder(List<DevelopmentMilestone> milestones)
        {
            var issues = new List<string>();

            for (int i = 1; i < milestones.Count; i++)
            {
                if (milestones[i].ChapterNumber <= milestones[i - 1].ChapterNumber)
                {
                    issues.Add($"里程碑章节顺序错误：第{milestones[i].ChapterNumber}章应该在第{milestones[i - 1].ChapterNumber}章之后");
                }
            }

            return issues;
        }

        /// <summary>
        /// 验证属性变化的合理性
        /// </summary>
        private async Task<List<string>> ValidateAttributeChangesAsync(
            List<DevelopmentMilestone> milestones, 
            Character character)
        {
            var issues = new List<string>();

            try
            {
                // 检查属性变化是否过于剧烈
                foreach (var milestone in milestones)
                {
                    foreach (var change in milestone.AttributeChanges)
                    {
                        if (change.Value.ToString().StartsWith("+"))
                        {
                            var incrementText = change.Value.ToString().Substring(1);
                            if (int.TryParse(incrementText, out var increment) && increment > 50)
                            {
                                issues.Add($"第{milestone.ChapterNumber}章：{change.Key}属性增长过快（+{increment}）");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "验证属性变化失败");
            }

            return issues;
        }

        /// <summary>
        /// 验证技能进展的合理性
        /// </summary>
        private List<string> ValidateSkillProgression(List<DevelopmentMilestone> milestones)
        {
            var issues = new List<string>();
            var learnedSkills = new HashSet<string>();

            foreach (var milestone in milestones)
            {
                foreach (var skill in milestone.NewSkills)
                {
                    if (learnedSkills.Contains(skill))
                    {
                        issues.Add($"第{milestone.ChapterNumber}章：重复学习技能 {skill}");
                    }
                    else
                    {
                        learnedSkills.Add(skill);
                    }
                }

                // 检查单个里程碑学习的技能数量
                if (milestone.NewSkills.Count > 3)
                {
                    issues.Add($"第{milestone.ChapterNumber}章：同时学习技能过多（{milestone.NewSkills.Count}个）");
                }
            }

            return issues;
        }

        /// <summary>
        /// 计算发展路径评分
        /// </summary>
        private double CalculateDevelopmentScore(CharacterDevelopmentPath developmentPath)
        {
            var score = 0.0;

            // 基于里程碑数量评分
            var milestoneCount = developmentPath.Milestones.Count;
            var milestoneScore = Math.Min(milestoneCount / 10.0, 1.0) * 30;

            // 基于发展的连贯性评分
            var continuityScore = CalculateContinuityScore(developmentPath.Milestones) * 40;

            // 基于发展的多样性评分
            var diversityScore = CalculateDiversityScore(developmentPath.Milestones) * 30;

            score = milestoneScore + continuityScore + diversityScore;

            return Math.Max(0, Math.Min(100, score));
        }

        /// <summary>
        /// 计算连贯性评分
        /// </summary>
        private double CalculateContinuityScore(List<DevelopmentMilestone> milestones)
        {
            if (milestones.Count < 2) return 0.5;

            var continuityScore = 1.0;
            
            // 检查章节号的连续性
            for (int i = 1; i < milestones.Count; i++)
            {
                var gap = milestones[i].ChapterNumber - milestones[i - 1].ChapterNumber;
                if (gap > 5) // 如果间隔超过5章，扣分
                {
                    continuityScore -= 0.1;
                }
            }

            return Math.Max(0, continuityScore);
        }

        /// <summary>
        /// 计算多样性评分
        /// </summary>
        private double CalculateDiversityScore(List<DevelopmentMilestone> milestones)
        {
            var totalAttributes = milestones.SelectMany(m => m.AttributeChanges.Keys).Distinct().Count();
            var totalSkills = milestones.SelectMany(m => m.NewSkills).Distinct().Count();
            
            var attributeDiversity = Math.Min(totalAttributes / 5.0, 1.0);
            var skillDiversity = Math.Min(totalSkills / 10.0, 1.0);

            return (attributeDiversity + skillDiversity) / 2;
        }

        /// <summary>
        /// 优化发展路径
        /// </summary>
        public async Task<CharacterDevelopmentPath> OptimizeDevelopmentPathAsync(
            CharacterDevelopmentPath originalPath, 
            DevelopmentValidationResult validationResult)
        {
            try
            {
                _logger.LogInformation("优化角色发展路径");

                var optimizedPath = new CharacterDevelopmentPath
                {
                    CharacterId = originalPath.CharacterId,
                    DevelopmentTheme = originalPath.DevelopmentTheme,
                    Milestones = new List<DevelopmentMilestone>(originalPath.Milestones)
                };

                // 根据验证结果进行优化
                foreach (var issue in validationResult.Issues)
                {
                    if (issue.Contains("章节顺序错误"))
                    {
                        // 重新排序里程碑
                        optimizedPath.Milestones = optimizedPath.Milestones
                            .OrderBy(m => m.ChapterNumber)
                            .ToList();
                    }
                    else if (issue.Contains("属性增长过快"))
                    {
                        // 调整属性增长幅度
                        await AdjustAttributeGrowthAsync(optimizedPath.Milestones);
                    }
                    else if (issue.Contains("重复学习技能"))
                    {
                        // 移除重复技能
                        RemoveDuplicateSkills(optimizedPath.Milestones);
                    }
                }

                return optimizedPath;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "优化发展路径失败");
                return originalPath;
            }
        }

        /// <summary>
        /// 调整属性增长幅度
        /// </summary>
        private async Task AdjustAttributeGrowthAsync(List<DevelopmentMilestone> milestones)
        {
            foreach (var milestone in milestones)
            {
                var adjustedChanges = new Dictionary<string, object>();
                
                foreach (var change in milestone.AttributeChanges)
                {
                    if (change.Value.ToString().StartsWith("+"))
                    {
                        var incrementText = change.Value.ToString().Substring(1);
                        if (int.TryParse(incrementText, out var increment) && increment > 50)
                        {
                            // 将过大的增长调整为合理范围
                            var adjustedIncrement = Math.Min(increment, 20);
                            adjustedChanges[change.Key] = $"+{adjustedIncrement}";
                        }
                        else
                        {
                            adjustedChanges[change.Key] = change.Value;
                        }
                    }
                    else
                    {
                        adjustedChanges[change.Key] = change.Value;
                    }
                }
                
                milestone.AttributeChanges = adjustedChanges;
            }
        }

        /// <summary>
        /// 移除重复技能
        /// </summary>
        private void RemoveDuplicateSkills(List<DevelopmentMilestone> milestones)
        {
            var learnedSkills = new HashSet<string>();
            
            foreach (var milestone in milestones)
            {
                var uniqueSkills = new List<string>();
                
                foreach (var skill in milestone.NewSkills)
                {
                    if (!learnedSkills.Contains(skill))
                    {
                        uniqueSkills.Add(skill);
                        learnedSkills.Add(skill);
                    }
                }
                
                milestone.NewSkills = uniqueSkills;
            }
        }
    }

    /// <summary>
    /// 发展验证结果
    /// </summary>
    public class DevelopmentValidationResult
    {
        public bool IsValid { get; set; }
        public double Score { get; set; }
        public List<string> Issues { get; set; } = new();
        public List<string> Suggestions { get; set; } = new();
        public DateTime ValidationTime { get; set; }
    }
}
